<?php
/**
 * Created by PhpStorm
 * User: whh
 * Date: 2022/8/24
 * Time: 15:50
 */

namespace app\common\classes\helper;


use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class SendMessage
{

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret)
    {
        $config = new Config([
            // 您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * @param string[] $args
     */
    public static function main($args, $accessKeyID = '', $accessKeySecret = '')
    {
        $sms_accessKeyID = $accessKeyID == '' ? config('sms_accessKeyID') : $accessKeyID;
        $sms_accessKeySecret = $accessKeySecret == '' ? config('sms_accessKeySecret') : $accessKeySecret;
        $client = self::createClient($sms_accessKeyID, $sms_accessKeySecret);
        $sendSmsRequest = new SendSmsRequest($args);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $res = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
            //大写警惕
            if ($res->body->code == 'OK') {
                return sucArr();
            } else {
                return errArr($res->body->message);
            }
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 如有需要，请打印 error
            $msg = Utils::assertAsString($error->message);
            return errArr($msg);
        }
    }
}
